/**
 * http://www.jxsrfdc.com/Publish/xmgs.aspx
 * 上饶房地产信息网扩展信息爬虫
 * sunny 2017-06-16
 */

import "./spider";
import * as cheerio from "cheerio";
import { Driver } from "./db";
// 工具类  
const utils = require('./utils');
const SpiderClass = require("./spider");

const srfdc_url: string = "http://www.jxsrfdc.com/Publish/ysgs.aspx";

let driver = new Driver();
let lpmcs: string[];
const title: string = "上饶房地产补充数据";
let spider: Spider = (new SpiderClass() as Spider);
lpmcs = driver.distinctSync("srfdcdetail", {}, "楼盘名称");
spider.getSync("http://www.jxsrfdc.com/index.aspx");

let getProvider = function (lpmc: string): string { //获取楼盘对应的开发商
    var form_data = {};
    var data = spider.getSync(srfdc_url);
    var $ = cheerio.load(data);
    $("#form1 input[type='hidden']").each(function (index, ele) {
        var $a = $(ele);
        (form_data as any)[$a.attr("name")] = $a.attr("value");
    });
    (form_data as any)["txtBox1"] = lpmc;
    (form_data as any)["txtBox2"] = "";
    (form_data as any)["btnSearch.x"] = Math.round(Math.random() * 100);
    (form_data as any)["btnSearch.y"] = Math.round(Math.random() * 100);
    console.log("楼盘名称:" + lpmc);
    var data2 = spider.postSync(srfdc_url, form_data);
    $ = cheerio.load(data2);
    var $b = $("table.btitle_ysgs td a").eq(0);
    var href = $b.attr("href");
    if (href) {
        var url = "http://www.jxsrfdc.com/Publish/" + href;
        console.log("url=>" + url);
        if (url) {
            var data3 = spider.getSync(url);
            $ = cheerio.load(data3);
            return $("#lbsfdw").text();
        }
    }
    return "";
};



for (var i = 0, j = lpmcs.length; i < j; i++) {
    let lpmc: string = lpmcs[i];
    let kfs: string = getProvider(lpmc);
    if (kfs != "") {
        if (driver.update("srfdcdetail", { "楼盘名称": lpmc }, { "开发商": kfs }) && driver.update("fdcxx", { "楼盘名称": lpmc }, { "开发商": kfs })) {
            console.log(lpmc + " -> " + kfs);
        } else {
            console.error(lpmc + " -> " + kfs + " error");
        }
    }
}

process.exit();